package com.vueblog.shiro;

import cn.hutool.json.JSONUtil;
import com.vueblog.common.Result;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtFilter extends AuthenticatingFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String jwt = request.getHeader(jwtUtils.getHeaderKey());
        if(StringUtils.isEmpty(jwt)) {
            return null;
        }
        return new JwtToken(jwt);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if(pathsMatch("/login", request)) {
            return true;
        }
        return super.isAccessAllowed(request, response, mappedValue);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String jwt = request.getHeader(jwtUtils.getHeaderKey());
        if(StringUtils.isEmpty(jwt)) {
            return true;
        }else{
            //检验jwt
            Claims claims = jwtUtils.getClaimsByToken(jwt);
            if(claims == null || jwtUtils.isTokenExpired(claims.getExpiration())) {
                //此处异常，不会进到GlobalExceptionHandler
                throw new ExpiredCredentialsException("token失效");
            }
            //登陆
            return executeLogin(servletRequest, servletResponse);
        }
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        Throwable throwable = e.getCause() == null ? e : e.getCause();
        Result result = Result.fail(throwable.getMessage());
        String json = JSONUtil.toJsonStr(result);
        HttpServletResponse res = (HttpServletResponse) response;
        res.setCharacterEncoding("UTF-8");
        res.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
        try {
            res.getWriter().write(json);
        } catch (IOException ioe) {
        }
        return false;
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpReq = WebUtils.toHttp(request);
        HttpServletResponse httpRes = WebUtils.toHttp(response);
        httpRes.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, httpReq.getHeader(HttpHeaders.ORIGIN));
        //httpRes.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, CorsConfiguration.ALL);
        httpRes.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,OPTIONS");
        httpRes.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, httpReq.getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS));
        if(RequestMethod.OPTIONS.name().equals(httpReq.getMethod())) {
            httpRes.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }
}
